package chaw.android.train;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;

public class FavoriteActivity extends ActivityGroup{
	public static ArrayList<String> mIdList;
	public final static int PROFILE_VIEW = 0;
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
        
		if(mIdList == null) {
			mIdList = new ArrayList<String>();
			startChildActivity("stationList", new Intent(getBaseContext(), FavoriteStationListActivity.class));
		}
	}
	
	public void test(){
		for(int i = 0 ; i < mIdList.size();i++){
			Log.v("d",mIdList.get(i));
		}
	}
	
	@Override
	public void finishFromChild(Activity child) {
		// TODO Auto-generated method stub
//		super.finishFromChild(child);
		LocalActivityManager manager = getLocalActivityManager();
		int index = mIdList.size()-1;

		if (index < 1) {
			finish();
			return;
		}
		
		manager.destroyActivity(mIdList.get(index), true);
		mIdList.remove(index);
		index--;
		
		try{
			String lastId = mIdList.get(index);
			Intent lastIntent = manager.getActivity(lastId).getIntent();
			
			Window newWindow = manager.startActivity(lastId, lastIntent);
			setContentView(newWindow.getDecorView());
		}catch (Exception e) {
			// TODO: handle exception
			finish();
		}
	}
	
	public void startChildActivity(String Id, Intent intent) {
		Window window = getLocalActivityManager().startActivity(Id,intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
		if (window != null) {
		mIdList.add(Id);
		setContentView(window.getDecorView());
		}
	}
	
	public void startChildActivityWithoutCurrentActivity(String Id, Intent intent) {
		Window window = getLocalActivityManager().startActivity(Id,intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
		if (window != null) {
			mIdList.remove(mIdList.size()-1);
			mIdList.add(Id);
			setContentView(window.getDecorView());
		}
	}

	@Override
	public void onBackPressed() {
		try{
			if(getLocalActivityManager().getActivity(mIdList.get(mIdList.size()-1)).getIntent().getExtras().getInt("flag") == FavoriteActivity.PROFILE_VIEW){
				finish();
			}
			else{
				finishFromChild(FavoriteActivity.this);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
//		if(getIntent().getFlags() == PROFILE_VIEW){
//			startChildActivity("Profile", getIntent());
//		}
//		else 
		if(mIdList.isEmpty())
			startChildActivity("stationList", new Intent(getBaseContext(), FavoriteStationListActivity.class));
	}
}
